package com.filter;

import com.alibaba.fastjson2.JSONObject;
import com.context.ManagerContext;
import com.context.ManagerInfoDTO;
import com.result.Result;
import com.result.Results;
import com.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class JwtFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //1.获取请求的url
        String url = req.getRequestURL().toString();

        //2.判断url中是否包含login
        if (url.contains("login")) {
            log.info("登录操作放行");
            chain.doFilter(request, response);
            return;
        }
       //3.判断url中是否包含register
        if (url.contains("register")) {
            log.info("注册操作放行");
            chain.doFilter(request, response);
            return;
        }

        //4.获取请求头中的令牌
        String jwt = req.getHeader("Token");

        //5.判断令牌是否为空
        if (!StringUtils.hasLength(jwt)) {

            resp.setCharacterEncoding("utf-8");
            Result<String> error = Results.error("用户未登录");
            String s = JSONObject.toJSONString(error);
            resp.getWriter().write(s);
            return;
        }

        //6.令牌不为空，校验令牌是否正确
        Claims claims;
        try {
            claims = JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCharacterEncoding("utf-8");
            Result<String> error = Results.error("用户未登录");
            String s = JSONObject.toJSONString(error);
            resp.getWriter().write(s);
            return;
        }

        //7.令牌正确，从令牌中取出管理员id 和 管理员名字，封装到上下文
        String username = (String) claims.get("username");
        Long managerId = (Long) claims.get("managerId");
        ManagerInfoDTO managerInfoDTO = new ManagerInfoDTO(managerId, username);
        ManagerContext.setUser(managerInfoDTO);

        //8.放行请求
        chain.doFilter(request, response);
    }
}
